package com.gaga.crm.controller;

import com.gaga.crm.base.config.shiro.MyShiroRealm;
import com.gaga.crm.pojo.SysRight;
import com.gaga.crm.pojo.SysRole;
import com.gaga.crm.pojo.SysUser;
import com.gaga.crm.service.SysRoleService;
import com.gaga.crm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@Controller
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private SysRoleService roleService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //redis 中数据的 key 的前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    @RequestMapping(value = "/doLogin")
    public String doLogin(String usrName, String usrPassword, HttpServletRequest request, Model model, HttpSession session) {
        try {
            /*usrPassword = userService.encryptPassword(usrPassword); //封装之前先进行加密*/
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录

            //认证(登录)成功，清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);

            //认证(登录)成功
            SysUser user = (SysUser) subject.getPrincipal();

            //获取权限
            SysRole role = user.getRole(); //如果一对多关联不是立即加载，则需要通过用户获取角色
            List<SysRight> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("loginUser", user);

            //清空权限缓存
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();


            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("message", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("message", "账号一小时内禁止登录！");
            return "login";
        }

    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();//Shiro 注销
        return "redirect:/login";//建议重定向，保证删除 Cookie
    }

    @RequestMapping(value = "/user/list")
    public String list(Model model, String usrName,
                       @RequestParam(required = false, defaultValue = "0") Long roleId,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex) {
        Sort sort = Sort.by(Sort.Direction.ASC, "usrId");
        //控制分页的辅助类，可以设置页码(从 0 开始！！！)、每页的数据条数、排序等
        Pageable pageable = PageRequest.of(pageIndex - 1, 5, sort);
        Page<SysUser> userPager = userService.findUsers(usrName, roleId, pageable);
        model.addAttribute("userPager", userPager);
        //数据回显
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        List<SysRole> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/list";
    }

    @RequestMapping(value = "/user/add")
    public String add(Model model) {
        List<SysRole> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    @RequestMapping(value = "/user/save")
    public String save(SysUser user) {
        userService.saveUser(user);
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/user/edit")
    //@RequiresPermissions(value = "L060104")   //与ShiroConfig中配置的权限效果一致
    public String edit(Long usrId, Model model) {
        SysUser user = userService.getUser(usrId);
        List<SysRole> roles = roleService.findAllRoles();
        model.addAttribute("user", user);
        model.addAttribute("roles", roles);
        return "user/edit";
    }

    @RequestMapping(value = "/user/del")
    @ResponseBody
    public Map del(Long usrId) {
        userService.deleteUser(usrId);
        Map map = new HashMap();
        map.put("delResult", "true");
        return map;
    }

    @RequestMapping(value = "/role/json")
    @ResponseBody
    public List<SysRole> findAllRoles() {
        List<SysRole> list = roleService.findAllRoles();
        return list;
    }

    @RequestMapping(value = "/403")
    public String unauthorized() {
        return "403";
    }

}